from fastapi import APIRouter,Depends
from fastapi.security import OAuth2PasswordRequestForm

from models import User
from scheams import UserIn_Pydantic,User_Pydantic,Response200,Response400,ResponseToken
from core import verify_password,create_access_token

login = APIRouter(tags=["认证相关"])

@login.post("/login",summary="登录")
async def user_login(form_data: OAuth2PasswordRequestForm = Depends()):
    if user := await User.get(username=form_data.username):
        if verify_password(form_data.password, user.password):
            token = create_access_token({"sub":user.username})
            return ResponseToken(data={"token":f"bearer {token}"},access_token=token)
    return Response400(msg="账号或密码错误")

@login.post("/register",summary="注册")
async def user_register(user: UserIn_Pydantic):
    user_obj = await User.filter(username=user.username).first()
    if user_obj:
        return Response400(msg="用户已存在")
    
    date = await User_Pydantic.from_tortoise_orm(await User.create(**user.dict()))
    if date:
        return Response200(data=user_obj,msg="注册成功")
    return Response400(msg="注册失败")

